package yxy.game.pm2.module.conquest;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import yxy.apple.logger.Logger;
import yxy.apple.util.redisson.RedisException;
import yxy.cherry.data.DataCenter;
import yxy.cherry.data.bean.levelreward;
import yxy.cherry.data.bean.privilege;
import yxy.cherry.data.script.fomula;
import yxy.game.pm2.bean.Privilege;
import yxy.game.pm2.bean.db.dao.MySQLCacheDAO;
import yxy.game.pm2.bean.module.PlayerModule;
import yxy.game.pm2.bean.module.RedisLock;
import yxy.game.pm2.module.tip.TipHandle;
import yxy.game.pm2.module.tip.TipType;
import yxy.game.pm2.module.vip.PrivilegeHandle;
import yxy.game.pm2.module.vip.PrivilegeHandle.PrivilegeType;

import java.util.ArrayList;
import java.util.Collection;
import java.util.concurrent.TimeUnit;

public class ConquestModule extends PlayerModule {
	// bean===========================================================================
	//缓存过期时间
	private static long expire = 1;
	private static TimeUnit expireTimeUnit = TimeUnit.DAYS;

	private int mapId;
	private int sweepTimes;
	private int sweepFreeTimes;
	private DateTime lastSweepTime;

	private ArrayList<Integer> levelReward = new ArrayList<>();// 改为已领取奖励

	public int getMapId() {
		return mapId;
	}

	public void setMapId(int mapId) {
		this.mapId = mapId;
	}

	public int getSweepTimes() {
		return sweepTimes;
	}

	public void setSweepTimes(int sweepTimes) {
		this.sweepTimes = sweepTimes;
	}

	public int getSweepFreeTimes() {
		return sweepFreeTimes;
	}

	public void setSweepFreeTimes(int sweepFreeTimes) {
		this.sweepFreeTimes = sweepFreeTimes;
	}

	public DateTime getLastSweepTime() {
		return lastSweepTime;
	}

	public void setLastSweepTime(DateTime lastSweepTime) {
		this.lastSweepTime = lastSweepTime;
	}

	public ArrayList<Integer> getLevelReward() {
		return levelReward;
	}

	public void setLevelReward(ArrayList<Integer> levelReward) {
		this.levelReward = levelReward;
	}

	// func===========================================================================

	/** 扫荡次数刷新 */
	private void update() {
		DateTime now = DateTime.now();
		if (getLastSweepTime() == null || !new LocalDate(now).equals(new LocalDate(getLastSweepTime()))) {
			try {
				if (tryLock()) {
					setLastSweepTime(now);
					setSweepTimes(0);
					setSweepFreeTimes(0);
					this.set();
				}
			} catch (Exception e) {
			} finally {
				unlock();
			}
		}
	}

	public boolean isPrivilege() {
		return new PrivilegeHandle().getPrivilegeByType(getPlayerCode(), PrivilegeType.征战扫荡次数).size() > 0;
	}

	/** 特权免费扫荡次数 */
	public int privilegeFreeTimes() {
		int privilegeTimes = 0;
		Collection<Privilege> privileges = new PrivilegeHandle().getPrivilegeByType(getPlayerCode(), PrivilegeType.征战扫荡次数);
		for (Privilege privilegeBean : privileges) {
			privilege data = DataCenter.getData(privilegeBean.getPrivilegeid(), privilege.class);
			privilegeTimes += data.getParameter()[0];
		}
		return privilegeTimes;
	}

	/** 特权收费扫荡次数 */
	public int privilegeChargeTimes() {
		int privilegeTimes = 0;
		Collection<Privilege> privileges = new PrivilegeHandle().getPrivilegeByType(getPlayerCode(), PrivilegeType.征战扫荡次数);
		for (Privilege privilegeBean : privileges) {
			privilege data = DataCenter.getData(privilegeBean.getPrivilegeid(), privilege.class);
			privilegeTimes += data.getParameter()[1];
		}
		return privilegeTimes;
	}

	/** 用于显示扫荡花费的扫荡次数 */
	public int sweeptimes() {
		int privilegeTimes = privilegeFreeTimes();// 特权免费次数
		int freetimes = getSweepFreeTimes();// 免费的扫荡次数
		if (freetimes <= privilegeTimes) {
			return 0;
		}
		int times = getSweepTimes() - freetimes + 1;
		return times < 0 ? 0 : times;
	}

	public int remainsweeptimes() {
		int maxtimes = fomula.征战快速作战每日次数.intValue();
		int privilegeTimes = privilegeChargeTimes();// 特权增加的收费次数
		int times = sweeptimes();
		int remain = maxtimes - times + privilegeTimes;
		return remain;
	}

	public void check() {
		int privilegeTimes = privilegeFreeTimes();// 特权次数
		int freetimes = getSweepFreeTimes();// 免费的扫荡次数
		new TipHandle().updateTip(getPlayerCode(), TipType.征战_扫荡按钮, freetimes <= privilegeTimes);
		checkLevelReward();
	}

	public void checkLevelReward() {
		Collection<levelreward> levelrewards = DataCenter.getAllData(levelreward.class).values();
		for (levelreward data : levelrewards) {
			if (data.getCondition() >= getMapId()) {
				continue;// 不可领取
			}
			boolean rewarded = false;
			for (int i = 0, size = getLevelReward().size(); i < size; i++) {
				int levelRewardId = getLevelReward().get(i);
				if (levelRewardId == data.getId()) {
					// 已经领过
					rewarded = true;
					break;
				}
			}
			if (rewarded) {
				continue;
			}
			new TipHandle().updateTip(getPlayerCode(), TipType.征战_通关奖励按钮, true);
			return;
		}
		new TipHandle().updateTip(getPlayerCode(), TipType.征战_通关奖励按钮, false);
	}

	// redis==========================================================================
	private static String key(String playerCode) {
		return String.format("PLAYER:%s:MODULE:CONQUEST", playerCode);
	}

	public void set() {
		try {
			String key1 = key(getPlayerCode());
			setv(key1, this);

			check();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	static public ConquestModule get(String playerCode) {
		try {
			String key1 = key(playerCode);
			ConquestModule module = getv(key1);
			if (module == null) {
				module = MySQLCacheDAO.getV(key1, ConquestModule.class);
				if (module != null) { //同步到redis
					module.set();
				}
			}

			if (module == null) {
				module = create(playerCode);
			}
			module.update();
			return module;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	static private ConquestModule create(String playerCode) {
		if (playerCode == null || playerCode.length() == 0) {
			try {
				throw new Exception("playerCode is null");
			} catch (Exception e) {
				Logger.create(ConquestModule.class).error(e);
				e.printStackTrace();
			}
		}

		DateTime now = DateTime.now();
		ConquestModule module = new ConquestModule();
		module.setPlayerCode(playerCode);
		module.setMapId(1);
		module.timeline().setStartTime(now);
		module.setLastSweepTime(now);
		module.set();

		TargetTaskModule.get(playerCode);// 关联目标任务

		return module;
	}

	//存储到数据库的方法
	public static void saveToDB(String playerCode) {
		try {
			String key = key(playerCode);
			if (touchBucket(key).isExists()) {
				ConquestModule conquestModule = getv(key);
				MySQLCacheDAO.setV(key, conquestModule);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	//从redis移走数据的操作
	public static void removeAllFromRedis(String playerCode) {
		try {
			touchBucket(key(playerCode)).delete();
		} catch (RedisException e) {
			e.printStackTrace();
		}
	}
	// lock==========================================================================

	@Override
	public String lockKey() {
		return String.format("lock:%s", key(getPlayerCode()));
	}

	public static RedisLock lock(String playerCode) {
		return getLock(String.format("lock:%s", key(playerCode)));
	}

}
